define(['jquery', 'bootstrap', 'backend', 'table', 'form', '/assets/addons/kuerp/layui/layui.js'], function ($, undefined, Backend, Table, Form, Layui) {

    var Controller = {
        index: function () {

            layui.use(['table','upload','form'], function(){
                var table = layui.table;
                upload = layui.upload;

                var storesList = Config.storesList;
                var stores = xmSelect.render({
                    el: '#stores',
                    language: Config.lang == 'zh-cn' ? 'zn' : 'en',
                    tips: __('Serial'),
                    paging: true,
                    tips: __('Please_select_warehouse'),
                    pageSize: 5,
                    filterable: true,
                    data: storesList
                });

                var goodsList = Config.goodsList;
                var goods = xmSelect.render({
                    el: '#goods',
                    language: Config.lang == 'zh-cn' ? 'zn' : 'en',
                    tips: __('Serial'),
                    paging: true,
                    tips: __('Please_select_goods'),
                    pageSize: 5,
                    filterable: true,
                    data: goodsList
                });

                var goodsTypeList = Config.goodsTypeList;
                var goodsType = xmSelect.render({
                    el: '#goodsType',
                    language: Config.lang == 'zh-cn' ? 'zn' : 'en',
                    tips: __('Serial'),
                    tips: __('Product_category'),
                    data: goodsTypeList
                });

                var rowspanstr = Config.rowspan;
                var jsObject = JSON.parse(rowspanstr);    //转换为json对象

                var rowspanstr2 = Config.rowlist;
                var jsObjects = JSON.parse(rowspanstr2);    //转换为json对象

                var store_str = [jsObject,jsObjects];
                table.render({
                    elem: '#table'
                    ,url:'kuerp/goods_stock/index'
                    ,parseData: function(res){ //res 即为原始返回的数据
                        return {
                            "code": 0, //解析接口状态
                            "msg": '', //解析提示文本
                            "count": res.total, //解析数据长度
                            "data": res.rows, //解析数据列表
                            "countArr": res.countArr //解析数据列表
                        };
                    }
                    ,toolbar: '#thisToolbar' //开启头部工具栏，并为其绑定左侧模板
                    ,defaultToolbar: [
                        {name:'filter', title: __('Filter')}, // 列筛选
                         {
                            name: 'exports',
                            title: __('Exports'),
                            onClick: function(obj) {
                              // 获得数据并清除临时字段
                              var data = table.clearCacheKey(obj.data);
                              // 当前示例配置项
                              var options = obj.config;

                              if(data.length > 0 || Object.keys(data).length > 0){
                                table.exportFile(options.id, null, 'csv');
                              }else{
                                layer.msg(__('No data'));
                              }
                             
                            }
                          },
                        {name:'print', title: __('Print')} // 打印
                    ]
                    ,totalRow: true
                    ,cellMinWidth: 100 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
                    ,text: {
                        none: __('No data'),
                        loading: __('Loading...'),
                    }
                    ,where: {
                        filter:JSON.stringify(getSearch()),
                        op:JSON.stringify({'id':'<'}),
                    }
                    ,cols: store_str,
                    done: function(res, curr, count){
                        if (res.count == 0 && !searchStatus) {
                            var html = '<div class="layui-none no-results"><span>' + __('Please enter search criteria and click search') + '</span></div>';
                            $(".layui-table-main").html(html);
                        }else{
                            var countArr = res.countArr;
                            var obj = this.elem.next();
                            $(countArr).each(function (k,v) {
                                obj.find('.layui-table-total td[data-field="unit_price'+v.id+'"] .layui-table-cell').text(v.unit_price_count);
                            })
                        }
                    }
                });

                upload.render({
                    elem: '#import'
                    ,url: 'ajax/upload'
                    ,done: function(res, index, upload){ //上传后的回调
                        if(res.code==1){
                            Fast.api.ajax("kuerp/goods_stock/import?file="+res.data.url, "",'',true);
                        }else{
                            Toastr.error(res.msg);
                        }
                    }
                    ,accept: 'file' //允许上传的文件类型
                    ,size: 10240 //最大允许上传的文件大小
                });

                //头工具栏事件
                table.on('toolbar(table)', function(obj){
                    var checkStatus = table.checkStatus(obj.config.id);
                    switch(obj.event){
                        case 'refresh':
                            table.reload('table', []);
                            break;
                        case 'add':
                            Fast.api.open("kuerp/goods_stock/add", __("Add"), {
                                callback:function(value){
                                    Controller.api.bindevent();
                                }
                            });
                            break;
                        case 'delAll':
                            var data = checkStatus.data;
                            var ids = '';
                            $(data).each(function (k,v) {
                                ids+=v.id+',';
                            });
                            Fast.api.ajax("kuerp/goods_stock/del?ids="+ids, "",'',true);
                            break;
                    }
                });

                //监听行工具事件
                table.on('tool(table)', function(obj){
                    var data = obj.data;
                    if(obj.event === 'del'){
                        $.ajax( {
                            url: "kuerp/goods_stock/del",
                            type: "POST",
                            data:{'ids':data.id},
                            success: function(res){
                                if(res.code==1){
                                    Toastr.success(__('Operation_successful'));
                                    setTimeout(function () {
                                        parent.location.reload();
                                    },1500)
                                }else{
                                    Toastr.error(res.msg);
                                }
                            }
                        });
                    } else if(obj.event === 'edit'){
                        Fast.api.open("kuerp/goods_stock/edit?ids="+data.id, __("Edit"));
                    }
                });
                function getSearch() {
                    var storesArr = stores.getValue();
                    var stores_id = '';
                    if(storesArr.length>0){
                        $(storesArr).each(function (k,v) {
                            if(stores_id===''){
                                stores_id += v.value;
                            }else{
                                stores_id += ','+v.value;
                            }
                        })
                    }
                    var goodsArr = goods.getValue();
                    var goods_id = '';
                    if(goodsArr.length>0){
                        $(goodsArr).each(function (k,v) {
                            if(goods_id===''){
                                goods_id += v.value;
                            }else{
                                goods_id += ','+v.value;
                            }
                        })
                    }

                    var goodsTypeArr = goodsType.getValue();
                    var goods_type_id = '';
                    if(goodsTypeArr.length>0){
                        $(goodsTypeArr).each(function (k,v) {
                            if(goods_type_id===''){
                                goods_type_id += v.value;
                            }else{
                                goods_type_id += ','+v.value;
                            }
                        })
                    }

                    var search = {};
                    if(stores_id!=''){
                        search.stores_id = stores_id;
                    }
                    if(goods_id!=''){
                        search.goods_id = goods_id;
                    }
                    if(goods_type_id!=''){
                        search.goods_type_id = goods_type_id;
                    }
                    var createtime = $('#createtime').val();
                    if(createtime!=''){
                        search.createtime = createtime;
                    }
                    if(stores_id=='' && goods_id=='' && createtime=='' && goods_type_id==''){
                        searchStatus = false;
                        search.id = 1;
                    }else{
                        searchStatus = true;
                    }
                    return search;
                }
                //搜索事件
                var searchStatus = false;
                $('#search').on('click', function () {
                    table.reload('table', {
                        where: {
                            filter:JSON.stringify(getSearch()),
                            op:JSON.stringify({'goods_id':'IN','stores_id':'IN','createtime':'BETWEEN','id':'<'}),
                        }
                    });
                });
            });
            Controller.api.bindevent();
        },

        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                layui.use('laydate', function(){
                    var laydate = layui.laydate;
                    laydate.render({
                         lang: Config.lang == 'zh-cn' ? 'cn' : 'en',
                        elem: '#createtime',
                        type: 'datetime',
                        range: true
                    });
                });

                Form.api.bindevent($("form[role=form]"), function(data, ret){
                    parent.location.reload();
                });
            }
        }
    };
    return Controller;
});